package net.rock.service;

import net.rock.mapper.PerformanceMapper;
import net.rock.pojo.SalesDay;
import net.rock.pojo.SalesVol;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

@Service
public class PerformanceService {
    @Autowired
    private PerformanceMapper performanceMapper;

    public List<SalesVol> fetchSalesVol() {
        return performanceMapper.fetchSalesVol();
    }

    public List<SalesDay> fetchSalesDay() {
        return performanceMapper.fetchSalesDay();
    }

    public byte[] exportXlsx() throws IOException {
        List<SalesVol> salesVols = fetchSalesVol();

        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet();  // 工作表

        // Row则对应Excel中的行，初始化所有行
        int size = salesVols.size();
        Row[] row = new Row[size + 1];
        for (int i = 0; i < size + 1; i++) {
            row[i] = sheet.createRow(i);
        }
        // Cell相当于单元格，也可以理解为列。因为数据需要三列，所以此处创建了3列
        // 第一行设值
        row[0].createCell(0).setCellValue("书本ID");
        row[0].createCell(1).setCellValue("书本名称");
        row[0].createCell(2).setCellValue("书本销量");
        // 从第二行开始设置值
        for (int i = 0; i < size; i++) {
            SalesVol vol = salesVols.get(i);
            row[i + 1].createCell(0).setCellValue(vol.getBookId());
            row[i + 1].createCell(1).setCellValue(vol.getTitle());
            row[i + 1].createCell(2).setCellValue(vol.getCnt());
        }

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        workbook.write(bos);
        byte[] bytes = bos.toByteArray();
        bos.close();
        return bytes;
    }
}
